<template>
  <div class="account-management">
    <h3>管理员账号管理</h3>
    
    <div class="account-list">

      <table class="account-table" v-if="paginatedAccounts.length > 0">
        <thead>
          <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>账号</th>
            <th>密码</th>
            <th>状态</th>
            <th>创建时间</th>
            <th class="action-header">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="account in paginatedAccounts" :key="account.maId">
            <td>{{ account.maId }}</td>
            <td>{{ account.maName }}</td>
            <td>{{ account.maAccount }}</td>
            <td>{{ account.maPassword }}</td>
            <td>{{ account.maIsUsing ? '启用' : '禁用' }}</td>
            <td>{{ formatDate(account.maTime) }}</td>
            <td class="action-cell" v-if="account.maIsUsing">
              <div class="action-buttons">
                <button class="edit-button" @click="editAccount(account)">编辑</button>
                <button 
                  class="disable-button" 
                  @click="changeAccountStatus(account.maId, false)">
                  禁用
                </button>
              </div>
            </td>
            <td class="action-cell" v-else>
              <button 
                class="enable-button" 
                @click="changeAccountStatus(account.maId, true)">
                恢复账号
              </button>
            </td>
          </tr>
        </tbody>
      </table>
      
      <div v-else class="no-data">
        <p>暂无管理员账号数据</p>
      </div>
      
      <!-- 分页组件 -->
      <div class="pagination" v-if="accounts.length > 0">
        <button 
          :disabled="currentPage === 1" 
          @click="prevPage"
          class="page-button"
        >
          上一页
        </button>
        
        <span class="page-info">
          第 {{ currentPage }} 页，共 {{ totalPages }} 页
        </span>
        
        <button 
          :disabled="currentPage === totalPages" 
          @click="nextPage"
          class="page-button"
        >
          下一页
        </button>
      </div>
    </div>
    
    <!-- 返回按钮 -->
    <div class="return-button-container">
      <button class="return-button" @click="returnToMenu">返回管理</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

interface ManagerAccount {
  maId: number
  maName: string
  maAccount: string
  maPassword: string
  maIsUsing: boolean
  maIsMain: boolean
  maTime: string
}

const accounts = ref<ManagerAccount[]>([])
const currentPage = ref(1)
const pageSize = 7 // 每页显示7条数据

// 计算分页后的数据
const paginatedAccounts = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize
  const endIndex = startIndex + pageSize
  return accounts.value.slice(startIndex, endIndex)
})

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(accounts.value.length / pageSize)
})

// 上一页
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

// 下一页
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
  }
}

// 从localStorage获取token
const token = localStorage.getItem('token')

// 获取管理员账号列表
const fetchAccounts = async () => {
  try {
    const response = await axios.get('http://localhost:8080/manager/getNOMainList',{
        headers: {
            'token': token
        }
    })
    if (response.data.success) {
      accounts.value = response.data.data
    }
  } catch (error) {
    console.error('获取管理员账号列表失败:', error)
  }
}

// 格式化时间
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN')
}

// 添加新管理员账号
const addNewAccount = () => {
  // TODO: 实现添加新管理员账号功能
  console.log('添加新管理员账号')
}

// 编辑管理员账号
const editAccount = (account: ManagerAccount) => {
  // 通过事件通知父组件切换到编辑页面
  const event = new CustomEvent('navigate-to-change-info', { detail: account })
  window.dispatchEvent(event)
}

// 更改管理员账号状态
const changeAccountStatus = async (managerId: number, isUsing: boolean) => {
  try {
    const formData = new FormData();
    formData.append('managerId', managerId.toString());
    formData.append('isUsing', isUsing.toString());
    
    const response = await axios.post('http://localhost:8080/manager/ChangeMAStatus', formData, {
      headers: {
        'token': token,
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (response.data.success) {
      // 更新本地状态
      const account = accounts.value.find(acc => acc.maId === managerId)
      if (account) {
        account.maIsUsing = isUsing
      }
      // 显示成功消息
      alert(isUsing ? '账号已恢复' : '账号已禁用')
    } else {
      // 显示错误消息
      alert('操作失败: ' + response.data.message)
    }
  } catch (error) {
    console.error('更改管理员账号状态失败:', error)
    alert('操作失败，请稍后重试')
  }
}

// 添加返回菜单的方法
const returnToMenu = () => {
  // 使用事件总线或直接操作父组件
  const event = new CustomEvent('navigate-to-menu')
  window.dispatchEvent(event)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchAccounts()
})
</script>

<style scoped>
.account-management {
  width: 100%;
  padding: 20px;
}

.account-management h2 {
  color: #333;
  font-size: 2rem;
  margin-bottom: 20px;
  text-align: center;
}

.toolbar {
  margin-bottom: 20px;
  text-align: right;
}

.add-button {
  padding: 10px 20px;
  background: linear-gradient(to right, #31B310, #2a990e);
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.add-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.account-table {
  width: 100%;
  border-collapse: collapse;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
}

.account-table th,
.account-table td {
  padding: 12px 15px;
  text-align: center;
  border-bottom: 1px solid #eee;
}

.action-header,
.action-cell {
  text-align: center;
}

.account-table th {
  background-color: #f8f9fa;
  font-weight: bold;
  color: #555;
}

.account-table tbody tr:hover {
  background-color: #f5f7fa;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 5px;
}

.edit-button,
.delete-button,
.disable-button,
.enable-button {
  padding: 5px 10px;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

.edit-button {
  background-color: #ffc107; /* 黄色 */
  color: #212529;
}

.disable-button {
  background-color: #dc3545; /* 红色 */
  color: white;
}

.enable-button {
  background-color: #007bff; /* 蓝色 */
  color: white;
  display: block;
  margin: 0 auto;
}

.delete-button {
  background-color: #6c757d; /* 灰色 */
  color: white;
}

.no-data {
  text-align: center;
  padding: 40px;
  color: #666;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  gap: 15px;
}

.page-button {
  padding: 8px 16px;
  background-color: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.page-button:hover:not(:disabled) {
  background-color: #e9ecef;
}

.page-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.page-info {
  font-size: 14px;
  color: #666;
}

.return-button-container {
  margin-top: 20px;
  text-align: center;
}

.return-button {
  padding: 10px 20px;
  background: linear-gradient(to right, #6c757d, #495057);
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.return-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
</style>